/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.web.rebate;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.config.client.ConfigClientProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.microsoft.windowsazure.exception.ServiceException;
import com.sigmatrix.h5.auth.H5Authenticator;
import com.sigmatrix.h5.entity.DisDealer;
import com.sigmatrix.h5.entity.DisDealerAcct;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.enums.SysResModule;
import com.sigmatrix.h5.properties.CookieProperties;
import com.sigmatrix.h5.service.DisDealerAcctService;
import com.sigmatrix.h5.service.DisDealerService;
import com.sigmatrix.h5.service.DisRebateScanCodeErrorService;
import com.sigmatrix.h5.service.DisRebateScanCodeService;
import com.sigmatrix.h5.service.ShortMessageService;
import com.sigmatrix.h5.service.UsersService;
import com.sigmatrix.h5.service.common.ServiceHelper;
import com.sigmatrix.h5.utils.Assert;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.MD5Utils;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.utils.security.TransPackageDTO;
import com.sigmatrix.h5.utils.security.TransferDecrypter;
import com.sigmatrix.h5.web.BaseController;
import com.sigmatrix.h5.web.Result;
import com.sigmatrix.h5.web.args.DealerInventoryPageParam;
import com.sigmatrix.h5.web.args.DealerLoginParam;
import com.sigmatrix.h5.web.args.LoginParam;
import com.sigmatrix.h5.web.args.WriteBackOpenIdParam;
import com.sigmatrix.h5.web.mode.DealerInventory;
import com.sigmatrix.h5.web.mode.DealerInventoryError;
import com.sigmatrix.h5.web.mode.Login;
import com.sigmatrix.h5.web.mode.VerCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *@ClassName: DisDealersAcctController
 *@Description: 经销商登录
 *@author MH
 *@date 2017年8月21日 下午9:38:37
 */
@Api(tags="经销商登录")
@RestController
@RequestMapping("/rebate/dealers")
public class DisDealersAcctController extends BaseController{

	@Autowired
	private H5Authenticator authenticator; 
	
	@Autowired
	private DisDealerAcctService disDealersAcctService; 
	@Autowired
	private UsersService usersService;
	@Autowired
	private DisDealerService distributionDealersService;
	
	@Autowired
	private DisRebateScanCodeService disRebateScanCodeService;
	
	@Autowired
	private DisRebateScanCodeErrorService disRebateScanCodeErrorService;
	
//	@Autowired
//	private ShortMessageService shortMessageService;
	
	@Autowired
	private CookieProperties cookieProperties;
	
	private String VER_CODE_COOKIE_KEY;

	@Value("${spring.application.name}")
	private String applicationName;
	
	@Autowired
	DisDealersAcctController(ConfigClientProperties configClientProperties) {
		VER_CODE_COOKIE_KEY = configClientProperties.getProfile()+"VerCode";
	}
	/**
	 * 经销商登录
	 *@Title: login
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月28日 上午11:11:59
	 *@param vo
	 *@return
	 */
	@ApiOperation("经销商登录")
	@PostMapping("/api/login")
	public Result<Login> login(@RequestBody DealerLoginParam vo){
		Assert.notNull(vo.getAccount(), "账号不能为空");
		Assert.notNull(vo.getPwd(), "密码不能为空");
		Assert.notNull(vo.getVerificationCode(), "验证码不能为空");
		try{
			if(!vilidateVerificationCode(vo.getVerificationCode())){
				return error("验证码不正确");
			}
		}catch(RuntimeException e){
			return error(e.getMessage());
		}
		
		LoginParam param = new LoginParam();
		param.setLoginName(vo.getAccount());
		param.setLoginPwd(vo.getPwd());
		param.setLoginType(SysResModule.REBATE.code);
		Login login = (Login) authenticator.login(param);
		
		return ok(login);
	}
	
//	@ApiOperation(value="经销商登录 登录接口2")
//	@PostMapping("/v2/api/login/type/{type}")
//	public Result<Login> crmLogin(@RequestBody DealerLoginParam vo,@PathVariable String type){
//		Assert.notNull(vo.getAccount(), "账号不能为空");
//		Assert.notNull(vo.getPwd(), "密码不能为空");
//		Assert.notNull(vo.getVerificationCode(), "验证码不能为空");
////		try{
////			if(!vilidateVerificationCode(vo.getVerificationCode())){
////				return error("验证码不正确");
////			}
////		}catch(RuntimeException e){
////			return error(e.getMessage());
////		}
//		LoginParam param = new LoginParam();
//		param.setLoginName(vo.getAccount());
//		param.setLoginPwd(vo.getPwd());
//		if("rebate".equals(type)){
//			param.setLoginType(SysResModule.REBATE.code);			
//		}else if("inspection".equals(type)){
//			param.setLoginType(SysResModule.INSPECTION.code);						
//		}else if("promotion".equals(type)){
//			param.setLoginType(SysResModule.PROMOTION_SCAN.code);									
//		}
//		Login login = (Login) dealerAuthenticator.login(param);
//		return ok(login);
//	}
	
//	@ApiOperation(value="登出2")
//	@PostMapping("/v2/api/logout")
//	public Result<Void> crmlogout(String token){
//		dealerAuthenticator.logout(token);
//		return ok(null);
//	}
	
	
	@ApiOperation("经销商登录，如果浏览器不支持cookie使用该接口")
	@PostMapping("/api/login/v2")
	public Result<Login> loginv2(@RequestBody DealerLoginParam vo){
		if(StringUtils.isBlank(vo.getAccount())){
			return error("账号不能为空");
		}
		if(StringUtils.isBlank(vo.getPwd())){
			return error("密码不能为空");
		}
		ServiceHelper.selectSmsService(null).validateCode(vo.getVerificationCode());
		LoginParam param = new LoginParam();
		param.setLoginName(vo.getAccount());
		param.setLoginPwd(vo.getPwd());
		param.setLoginType(SysResModule.PROMOTION_SCAN.code+","+SysResModule.VERIFICATION.code);
		Login login = (Login) authenticator.login(param);
//		Login login = usersService.login(vo.getAccount(),vo.getPwd(),SysResModule.PROMOTION_SCAN);
		return ok(login);
	}
	
	@ApiOperation("重置密码发送短信验证码")
	@GetMapping("/api/h5/reset/message")
	public Result<DisDealerAcct> resetPwdSendMessage(String acct){
		DisDealerAcct user = ServiceHelper.selectSmsService(null).sendMessageByAcct(acct);
		return ok(user);
	}
	@ApiOperation("修改密码")
	@PostMapping("/api/h5/reset/pwd")
	public Result<String> resetPwd(@RequestBody DealerLoginParam vo){
		ServiceHelper.selectSmsService(null).validateCode(vo.getVerificationCode());
		usersService.updatePwdByAcct(vo.getAccount(), vo.getPwd());
		return ok("修改成功");
	}
	/**
	 * 
	 *@Title: logout
	 *@Description:登出 
	 *@return Result
	 *@author MH
	 *@date 2017年12月19日 下午2:20:34
	 *@param token
	 *@return
	 */
	@ApiOperation("登出，失效token")
	@PostMapping("/api/logout")
	public Result<Void> logout(String token){
//		usersService.logout(token);
		authenticator.logout(token);
		return ok(null);
	}
	private boolean vilidateVerificationCode(String verificationCode){
		Cookie[] cookies = request.getCookies();
		if(CommonUtils.isEmpty(cookies)){
			throw new RuntimeException("获取cookie失败");
		}
		boolean h = false;
		for (Cookie cookie : cookies) {
			if(VER_CODE_COOKIE_KEY.equals(cookie.getName())){
				h = true;
				if(verificationCode.equalsIgnoreCase(cookie.getValue())){
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					return true;
				}
				return false;
			}
		}
		if(!h){
			throw new RuntimeException("验证码不存在");
		}
		return false;
	}
	/**
	 * 解密openId
	 *@Title: decrypt
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月28日 下午2:39:08
	 *@param data
	 *@return
	 */
	@ApiOperation("解密openId")
	@PostMapping("/api/decrypt")
	public Result<TransPackageDTO> decrypt(String data){
		if(StringUtils.isBlank(data)){
			return error("解密串不能为空");
		}
		try {
			TransPackageDTO dto = TransferDecrypter.decodeTransferData(data);
			if(CommonUtils.isEmpty(dto)){
				return error("解密失败");
			}
			return ok(dto);
		} catch (Exception e) {
			return error("解密失败");
		}
	}
	
	/**
	 * 获取公众号
	 *@Title: getAppId
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月28日 上午11:12:19
	 *@param eseId
	 *@return
	 */
//	@ApiOperation("获取公众号")
//	@GetMapping("/api/getAppId")
//	public Result getAppId(Integer eseId){
//		try {
//			return disDealersAcctService.getAppId(eseId);
//		} catch (ServiceException e) {
//			e.printStackTrace();
//			return FAILURE();
//		}
//		
//	}
	/**
	 * 反写openId
	 *@Title: writeBackOpenId
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月28日 下午2:21:27
	 *@param vo
	 *@return
	 */
	@ApiOperation("反写openId")
	@PostMapping("/api/writeBackOpenId")
	public Result<Void> writeBackOpenId(@RequestBody WriteBackOpenIdParam vo){
		if(CommonUtils.isEmpty(vo)){
			return error("参数不能为空");
		}
		if(CommonUtils.isEmpty(vo.getId())){
			return error("经销商账号ID不能为空");
		}
		if(CommonUtils.isEmpty(vo.getOpenId()) || "null".equals(vo.getOpenId())){
			return error("openId不能为空");
		}
		final DisDealerAcct acct = new DisDealerAcct();
		BeanUtils.copyProperties(vo, acct);
		disDealersAcctService.updateSelective(acct);
		return ok(null);
	}
	/**
	 * 获取经销商信息
	 *@Title: getDealersInfo
	 *@Description: 
	 *@return Result
	 *@author MH
	 *@date 2017年8月29日 下午5:40:14
	 *@param dealerId
	 *@return
	 */
	@ApiOperation("获取经销商信息")
	@PostMapping("/api/getDealersInfo")
	public Result<DisDealer> getDealersInfo(Integer dealerId){
		if(CommonUtils.isEmpty(dealerId)){
			return error("经销商ID不能为空");
		}
		DisDealer dealer = distributionDealersService.getDealerInfo(dealerId);
		if(CommonUtils.isNotEmpty(dealer)){
			return ok(dealer);
		}else{
			return error("没有查询到记录");
		}
	}
	@ApiOperation("获取验证码")
	@PostMapping("/api/vercode")
	public Result<VerCode> verilicationCode(){
		VerCode code = usersService.generateVerCode();
		setCookie(code.getValue());
		return ok(code);
	}
	@ApiOperation("修改密码")
	@PostMapping("/api/pwd")
	public Result<Void> verilicationCode(String pwd) throws ServiceException{
		if(StringUtils.isBlank(pwd))return error("新密码不能为空");
		DisDealerAcct acct = new DisDealerAcct();
		acct.setId(SessionUtils.getUserId());
		acct.setPwd(MD5Utils.getMD5Code(pwd));
		disDealersAcctService.updateSelective(acct);
		return ok(null);
	}
	
	private void setCookie(String value){
		Cookie cookie = new Cookie(VER_CODE_COOKIE_KEY, value);
		cookie.setDomain(cookieProperties.getDomain());
		cookie.setPath("/"+applicationName);
		response.addCookie(cookie);
	}
	
	/**
	 * 
	 * @param vo
	 * @return
	 */
	@ApiOperation("查询当前登录用户和其下级用户扫码记录")
	@PostMapping("/inventory/page")
	public Result<DealerInventory> findByPage(@RequestBody DealerInventoryPageParam vo){
		if (CrmAcctType.TERMINAL_SHOP.value.equals(SessionUtils.getAcctType())) {
			if(CommonUtils.isEmpty(SessionUtils.getTerminalShopId())){
				return error("门店账号id不能为空");
			}
			vo.setDealerId(SessionUtils.getTerminalShopId());
			vo.setDealerType(CrmAcctType.TERMINAL_SHOP.value);
		}else if(CrmAcctType.DEALER.value.equals(SessionUtils.getAcctType())) {
			if(CommonUtils.isEmpty(SessionUtils.getDealerId())){
				return error("经销商账号id不能为空");
			}
			vo.setDealerId(SessionUtils.getDealerId());
			vo.setDealerType(CrmAcctType.DEALER.value);
		}else {
			return error("此账户类型暂不支持查看扫码记录");
		}
		return ok(disRebateScanCodeService.findDealerInventory(vo));
	}
	
	/**
	 * 
	 * @param vo
	 * @return
	 */
	@ApiOperation("扫码错误列表")
	@PostMapping("/inventory/info")
	public Result<DealerInventoryError> findInfo(@RequestBody DealerInventoryPageParam vo){
		if (CrmAcctType.TERMINAL_SHOP.value.equals(SessionUtils.getAcctType())) {
			if(CommonUtils.isEmpty(SessionUtils.getTerminalShopId())){
				return error("门店账号id不能为空");
			}
			vo.setDealerId(SessionUtils.getTerminalShopId());
			vo.setDealerType(CrmAcctType.TERMINAL_SHOP.value);
		}else if(CrmAcctType.DEALER.value.equals(SessionUtils.getAcctType())) {
			if(CommonUtils.isEmpty(SessionUtils.getDealerId())){
				return error("经销商账号id不能为空");
			}
			vo.setDealerId(SessionUtils.getDealerId());
			vo.setDealerType(CrmAcctType.DEALER.value);
		}else {
			return error("此账户类型暂不支持查看扫码记录");
		}
		return ok(disRebateScanCodeErrorService.findDealerInventoryError(vo));
	}
	
	@ApiOperation("通过账号密码查询")
	@GetMapping("/api/info")
	public Result<DisDealerAcct> findByAcctAndPwd(String acct,String pwd){
		Assert.notNull(acct,pwd,"账号/密码不能为空");
		DisDealerAcct user = usersService.findByAcctAndPwd(acct,pwd);
		return ok(user);
	}
	
	/**
	 * 
	 *@Title: loadUserInfo
	 *@Description:加载当前登录的而用户信息
	 *@return Result<Login>
	 *@author MH
	 *@date 2018年3月1日 上午10:59:03
	 *@return
	 */
	@ApiOperation("通过账号密码查询")
	@GetMapping("/api/load")
	public Result<DisDealerAcct> loadUserInfo(){
		DisDealerAcct acct = disDealersAcctService.findById(SessionUtils.getUserId());
		acct.setPwd(null);
		return ok(acct);
	}
}
